using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Volo.Abp.Application.Services;
using Volo.Abp.Caching;
using UserSystemService.Application.DTOs;
using UserSystemService.Application.Users;

namespace Matrix.Bff.Application.Aggregators
{
    /// <summary>
    /// 用户聚合器
    /// 整合用户相关的多个服务数据，提供统一的用户信息接口
    /// </summary>
    public class UserAggregator : ApplicationService
    {
        private readonly IUserAppService _userAppService;
        private readonly ILogger<UserAggregator> _logger;
        private readonly IDistributedCache<UserProfileDto> _profileCache;

        public UserAggregator(
            IUserAppService userAppService,
            ILogger<UserAggregator> logger,
            IDistributedCache<UserProfileDto> profileCache)
        {
            _userAppService = userAppService;
            _logger = logger;
            _profileCache = profileCache;
        }

        /// <summary>
        /// 获取用户完整档案信息
        /// </summary>
        public async Task<UserProfileDto> GetUserProfileAsync(Guid userId)
        {
            var cacheKey = $"UserProfile:{userId}";
            var cachedProfile = await _profileCache.GetAsync(cacheKey);

            if (cachedProfile != null)
            {
                _logger.LogDebug("从缓存获取用户档案: {UserId}", userId);
                return cachedProfile;
            }

            try
            {
                _logger.LogInformation("开始聚合用户档案信息: {UserId}", userId);

                // 并行获取各种用户信息
                var tasks = new[]
                {
                    GetBasicUserInfoAsync(userId),
                    GetUserPermissionsAsync(userId),
                    GetUserOrganizationsAsync(userId),
                    GetUserKeycloakScopesAsync(userId),
                    GetUserRecentActivityAsync(userId)
                };

                var results = await Task.WhenAll(tasks);

                var userProfile = new UserProfileDto
                {
                    UserId = userId,
                    BasicInfo = results[0],
                    Permissions = results[1],
                    Organizations = results[2],
                    KeycloakScopes = results[3],
                    RecentActivity = results[4],
                    LastUpdated = DateTime.UtcNow
                };

                // 缓存30分钟
                await _profileCache.SetAsync(cacheKey, userProfile, new Microsoft.Extensions.Caching.Distributed.DistributedCacheEntryOptions
                {
                    AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(30)
                });

                _logger.LogInformation("用户档案聚合完成: {UserId}, 权限数: {PermissionCount}, 组织数: {OrgCount}",
                    userId, userProfile.Permissions?.Count ?? 0, userProfile.Organizations?.Count ?? 0);

                return userProfile;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "聚合用户档案失败: {UserId}", userId);
                throw;
            }
        }

        /// <summary>
        /// 获取用户基础信息
        /// </summary>
        private async Task<UserBasicInfoDto> GetBasicUserInfoAsync(Guid userId)
        {
            try
            {
                var userDto = await _userAppService.GetAsync(userId);

                return new UserBasicInfoDto
                {
                    Id = userDto.Id,
                    Username = userDto.Username,
                    Email = userDto.Email,
                    Name = userDto.Name,
                    Surname = userDto.Surname,
                    FullName = $"{userDto.Name} {userDto.Surname}".Trim(),
                    AvatarUrl = userDto.AvatarUrl,
                    PhoneNumber = userDto.PhoneNumber,
                    Status = userDto.Status,
                    EmailConfirmed = userDto.EmailConfirmed,
                    PhoneNumberConfirmed = userDto.PhoneNumberConfirmed,
                    LastLoginTime = userDto.LastLoginTime,
                    LastLoginIp = userDto.LastLoginIp,
                    CreationTime = userDto.CreationTime,
                    TenantId = userDto.TenantId
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取用户基础信息失败: {UserId}", userId);
                return null;
            }
        }

        /// <summary>
        /// 获取用户权限信息
        /// </summary>
        private async Task<UserPermissionsDto> GetUserPermissionsAsync(Guid userId)
        {
            try
            {
                var permissions = await _userAppService.GetUserPermissionsAsync(userId);

                // 按模块分组权限
                var groupedPermissions = GroupPermissionsByModule(permissions);

                return new UserPermissionsDto
                {
                    TotalCount = permissions.Count,
                    Permissions = permissions,
                    GroupedPermissions = groupedPermissions,
                    LastSyncTime = DateTime.UtcNow
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取用户权限失败: {UserId}", userId);
                return new UserPermissionsDto { TotalCount = 0, Permissions = new List<string>() };
            }
        }

        /// <summary>
        /// 获取用户组织信息
        /// </summary>
        private async Task<UserOrganizationsDto> GetUserOrganizationsAsync(Guid userId)
        {
            try
            {
                var userDto = await _userAppService.GetAsync(userId);

                return new UserOrganizationsDto
                {
                    TotalCount = userDto.Organizations?.Count ?? 0,
                    Organizations = userDto.Organizations ?? new List<UserOrganizationDto>(),
                    HasManagerRole = userDto.Organizations?.Any(org => org.IsManager) ?? false
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取用户组织信息失败: {UserId}", userId);
                return new UserOrganizationsDto { TotalCount = 0, Organizations = new List<UserOrganizationDto>() };
            }
        }

        /// <summary>
        /// 获取用户Keycloak Scope信息
        /// </summary>
        private async Task<UserKeycloakScopesDto> GetUserKeycloakScopesAsync(Guid userId)
        {
            try
            {
                var scopeBindings = await _userAppService.GetScopeBindingsAsync(userId, new Volo.Abp.Application.Dtos.PagedAndSortedResultRequestDto { MaxResultCount = 100 });

                return new UserKeycloakScopesDto
                {
                    TotalCount = (int)scopeBindings.TotalCount,
                    Scopes = scopeBindings.Items,
                    HasActiveScopes = scopeBindings.Items.Any(sb => sb.IsActive),
                    LastValidationTime = DateTime.UtcNow
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取用户Keycloak Scope失败: {UserId}", userId);
                return new UserKeycloakScopesDto { TotalCount = 0, Scopes = new List<KeycloakScopeBindingDto>() };
            }
        }

        /// <summary>
        /// 获取用户最近活动
        /// </summary>
        private async Task<UserRecentActivityDto> GetUserRecentActivityAsync(Guid userId)
        {
            try
            {
                var loginHistory = await _userAppService.GetLoginHistoryAsync(userId, new Volo.Abp.Application.Dtos.PagedAndSortedResultRequestDto { MaxResultCount = 5 });

                return new UserRecentActivityDto
                {
                    RecentLogins = loginHistory.Items,
                    LoginCount = (int)loginHistory.TotalCount,
                    LastLoginTime = loginHistory.Items.FirstOrDefault()?.LoginTime
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取用户最近活动失败: {UserId}", userId);
                return new UserRecentActivityDto { RecentLogins = new List<UserLoginHistoryDto>(), LoginCount = 0 };
            }
        }

        /// <summary>
        /// 按模块分组权限
        /// </summary>
        private Dictionary<string, List<string>> GroupPermissionsByModule(List<string> permissions)
        {
            var groupedPermissions = new Dictionary<string, List<string>>();

            foreach (var permission in permissions)
            {
                var module = GetPermissionModule(permission);

                if (!groupedPermissions.ContainsKey(module))
                {
                    groupedPermissions[module] = new List<string>();
                }

                groupedPermissions[module].Add(permission);
            }

            return groupedPermissions;
        }

        /// <summary>
        /// 根据权限名称获取模块
        /// </summary>
        private string GetPermissionModule(string permission)
        {
            if (permission.StartsWith("Photos."))
                return "相册管理";
            if (permission.StartsWith("Users.") || permission.StartsWith("Roles."))
                return "用户管理";
            if (permission.StartsWith("Tenants."))
                return "租户管理";
            if (permission.StartsWith("Files."))
                return "文件管理";
            if (permission.StartsWith("System."))
                return "系统管理";
            if (permission.StartsWith("Reports."))
                return "报表管理";
            if (permission.StartsWith("Settings."))
                return "系统设置";

            return "其他权限";
        }

        /// <summary>
        /// 清除用户档案缓存
        /// </summary>
        public async Task ClearUserProfileCacheAsync(Guid userId)
        {
            var cacheKey = $"UserProfile:{userId}";
            await _profileCache.RemoveAsync(cacheKey);
            _logger.LogInformation("清除用户档案缓存: {UserId}", userId);
        }

        /// <summary>
        /// 批量获取用户档案信息
        /// </summary>
        public async Task<List<UserProfileDto>> GetUserProfilesAsync(List<Guid> userIds)
        {
            var profiles = new List<UserProfileDto>();

            foreach (var userId in userIds)
            {
                try
                {
                    var profile = await GetUserProfileAsync(userId);
                    profiles.Add(profile);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "获取用户档案失败: {UserId}", userId);
                    // 继续处理其他用户
                }
            }

            return profiles;
        }

        /// <summary>
        /// 验证用户权限完整性
        /// </summary>
        public async Task<PermissionIntegrityCheckDto> CheckUserPermissionIntegrityAsync(Guid userId)
        {
            try
            {
                // 获取ABP权限
                var abpPermissions = await _userAppService.GetUserPermissionsAsync(userId);

                // 获取Keycloak Scope
                var scopeResult = await _userAppService.ValidatePermissionConsistencyAsync(userId);

                var checkResult = new PermissionIntegrityCheckDto
                {
                    UserId = userId,
                    AbpPermissionsCount = abpPermissions.Count,
                    KeycloakScopesCount = scopeResult.ValidScopes.Count,
                    IsConsistent = scopeResult.IsConsistent,
                    MissingScopes = scopeResult.MissingScopes,
                    ExtraScopes = scopeResult.ExtraScopes,
                    CheckTime = DateTime.UtcNow
                };

                _logger.LogInformation("用户权限完整性检查完成: {UserId}, 一致性: {IsConsistent}",
                    userId, checkResult.IsConsistent);

                return checkResult;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "检查用户权限完整性失败: {UserId}", userId);
                return new PermissionIntegrityCheckDto
                {
                    UserId = userId,
                    IsConsistent = false,
                    CheckTime = DateTime.UtcNow,
                    ErrorMessage = ex.Message
                };
            }
        }
    }

    /// <summary>
    /// 用户档案DTO
    /// </summary>
    public class UserProfileDto
    {
        public Guid UserId { get; set; }
        public UserBasicInfoDto BasicInfo { get; set; }
        public UserPermissionsDto Permissions { get; set; }
        public UserOrganizationsDto Organizations { get; set; }
        public UserKeycloakScopesDto KeycloakScopes { get; set; }
        public UserRecentActivityDto RecentActivity { get; set; }
        public DateTime LastUpdated { get; set; }
    }

    /// <summary>
    /// 用户基础信息DTO
    /// </summary>
    public class UserBasicInfoDto
    {
        public Guid Id { get; set; }
        public string Username { get; set; }
        public string Email { get; set; }
        public string Name { get; set; }
        public string Surname { get; set; }
        public string FullName { get; set; }
        public string AvatarUrl { get; set; }
        public string PhoneNumber { get; set; }
        public UserStatus Status { get; set; }
        public bool EmailConfirmed { get; set; }
        public bool PhoneNumberConfirmed { get; set; }
        public DateTime? LastLoginTime { get; set; }
        public string LastLoginIp { get; set; }
        public DateTime CreationTime { get; set; }
        public Guid? TenantId { get; set; }
    }

    /// <summary>
    /// 用户权限DTO
    /// </summary>
    public class UserPermissionsDto
    {
        public int TotalCount { get; set; }
        public List<string> Permissions { get; set; }
        public Dictionary<string, List<string>> GroupedPermissions { get; set; }
        public DateTime LastSyncTime { get; set; }
    }

    /// <summary>
    /// 用户组织DTO
    /// </summary>
    public class UserOrganizationsDto
    {
        public int TotalCount { get; set; }
        public List<UserOrganizationDto> Organizations { get; set; }
        public bool HasManagerRole { get; set; }
    }

    /// <summary>
    /// 用户Keycloak Scopes DTO
    /// </summary>
    public class UserKeycloakScopesDto
    {
        public int TotalCount { get; set; }
        public List<KeycloakScopeBindingDto> Scopes { get; set; }
        public bool HasActiveScopes { get; set; }
        public DateTime LastValidationTime { get; set; }
    }

    /// <summary>
    /// 用户最近活动DTO
    /// </summary>
    public class UserRecentActivityDto
    {
        public List<UserLoginHistoryDto> RecentLogins { get; set; }
        public int LoginCount { get; set; }
        public DateTime? LastLoginTime { get; set; }
    }

    /// <summary>
    /// 权限完整性检查DTO
    /// </summary>
    public class PermissionIntegrityCheckDto
    {
        public Guid UserId { get; set; }
        public int AbpPermissionsCount { get; set; }
        public int KeycloakScopesCount { get; set; }
        public bool IsConsistent { get; set; }
        public List<string> MissingScopes { get; set; }
        public List<string> ExtraScopes { get; set; }
        public DateTime CheckTime { get; set; }
        public string ErrorMessage { get; set; }
    }
}